package com.jsy.search.controller;

import com.jsy.common.vo.Page;
import com.jsy.search.feign.SkuEsFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SkuEsFeign skuEsFeign;

    @GetMapping
    public ModelAndView search(@RequestParam(required = false) Map<String, String> searchMap) {
        ModelAndView mv = new ModelAndView("search");
        Map resultMap = skuEsFeign.search(searchMap);
        mv.addObject("resultMap", resultMap);
        mv.addObject("searchMap", searchMap);

        //将请求参数转换拼接到一个地址中
        //返回请求地址url
        String[] urls = mapToUrl(searchMap);
        mv.addObject("url", urls[0]);
        //返回排序请求地址url
        mv.addObject("sortUrl", urls[1]);
        //构造分页信息对象 页号 pageNum从0开始，要转成从1开始
        String pageNum = resultMap.get("pageNum").toString();
        pageNum = Integer.parseInt(pageNum) + 1 + "";
        Page page = new Page(pageNum, resultMap.get("pageSize").toString(), resultMap.get("total").toString(), resultMap.get("totalPage").toString());
        mv.addObject("page", page);
        return mv;
    }

    private String[] mapToUrl(Map<String, String> searchMap) {
        //处理映射路径
        String url = "/search";
        //用于排序的url,每次点击才添加排序信息，所以要过滤掉排序信息，重新排序
        String sortUrl = "/search";
        if (searchMap != null && searchMap.size() > 0) {
            url += "?";
            sortUrl += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                //过滤价格
                if ("price".equals(entry.getKey())) {
                    continue;
                }
                //过滤排序
                if ("sortField".equals(entry.getKey()) || "sortRule".equals(entry.getKey())) {
                    continue;
                }
                //过滤分页
                if ("pageNum".equals(entry.getKey()) || "pageSize".equals(entry.getKey())) {
                    continue;
                }
                url += entry.getKey() + "=" + entry.getValue() + "&";
                sortUrl += entry.getKey() + "=" + entry.getValue() + "&";
            }
            //去掉最后一个&
            url = url.substring(0, url.length() - 1);
            sortUrl = url.substring(0, sortUrl.length() - 1);
        }
        return new String[]{url, sortUrl};
    }


}
